package com.promise.jokerdream.work.signin.after

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 活跃度工作
class LivenessWork(uin: String): BaseWork(uin) {

    override val name: String
        get() = "活跃度"

    override val priority: Int
        get() = 8

    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        // 1. 查询活跃度状态
        val queryResult = gameApi.queryLiveness()
        queryResult.foldWithApiException(
            onSuccess = { response ->
                val currentLiveness = response.getCurrentLiveness()
                
                // 2. 检查并领取活跃度礼包（20、50、80、115）
                val thresholds = listOf(20, 50, 80, 115)
                thresholds.forEachIndexed { index, threshold ->
                    if (currentLiveness >= threshold && !response.isGiftClaimed(index + 1)) {
                        val giftResult = gameApi.getLivenessGift(index + 1)
                        giftResult.foldWithApiException(
                            onSuccess = { giftResponse ->
                                historyManager.addHistory(name, giftResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                }
                
                // 3. 检查并领取帮派活跃度礼包
                if (currentLiveness >= 65) {
                    val factionGiftResult = gameApi.getFactionLivenessGift()
                    factionGiftResult.foldWithApiException(
                        onSuccess = { factionResponse ->
                            historyManager.addHistory(name, factionResponse.getDescription())
                        },
                        onFailure = { code, msg ->
                            if (msg != "你今天已经领取过了！") {
                                historyManager.addHistory(name, msg, code)
                            }
                        }
                    )
                }
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg, code)
            }
        )

        return WorkResult.Success
    }
}